package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.GC.LatencyRequest;
@WebServlet("/lastAccessTime")
public class LastAccessTimeServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_hh:mm:ss");
		String time = format.format(date);
		Cookie cookie = new Cookie("lastAccessTime", time);
		resp.addCookie(cookie);
		
		Cookie[] cookies = req.getCookies();
		String lastAccessTime = null;
		if (null != cookie) {
			for (Cookie coo : cookies) {
				if ("lastAccessTime".equals(coo.getName())) {
					lastAccessTime = coo.getValue();
					System.out.println(lastAccessTime);
				}
			}
		}
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter printWriter = resp.getWriter();
		if (null == lastAccessTime) {
			printWriter.write("您是第一次访问");
		}else {
			printWriter.write("上次访问时间：" + lastAccessTime);
		}
		printWriter.close();
	}
}
